
$(document).ready(function(){



    $("#datepicker").datepicker({
        dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sa'],
        monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
        firstDay: 1,
        dateFormat: 'dd/mm/yy'
        
    });

    $('#timepicker').timepicker({
        // Options
        timeSeparator: ':',           // The character to use to separate hours and minutes. (default: ':')
        showLeadingZero: false,       // Define whether or not to show a leading zero for hours < 10. (default: true)
        showMinutesLeadingZero: true, // Define whether or not to show a leading zero for minutes < 10. (default: true)
        showPeriod: false,            // Define whether or not to show AM/PM with selected time. (default: false)
        showPeriodLabels: false,      // Define if the AM/PM labels on the left are displayed. (default: true)
        periodSeparator: ' ',         // The character to use to separate the time from the time period.
        altField: '#alternate_input', // Define an alternate input to parse selected time to
        defaultTime: '12:34',         // Used as default time when input field is empty or for inline timePicker
        // (set to 'now' for the current time, '' for no highlighted time, default value: now)

        zIndex: null,                 // Overwrite the default zIndex used by the time picker

        // trigger options
        showOn: 'focus',              // Define when the timepicker is shown.
        // 'focus': when the input gets focus, 'button' when the button trigger element is clicked,
        // 'both': when the input gets focus and when the button is clicked.
        button: null,                 // jQuery selector that acts as button trigger. ex: '#trigger_button'

        // Localization
        hourText: 'Horas',             // Define the locale text for "Hours"
        minuteText: 'Minutos',         // Define the locale text for "Minute"
        amPmText: ['AM', 'PM'],       // Define the locale text for periods

        // Events
        //     onSelect: onSelectCallback,   // Define a callback function when an hour / minutes is selected.
        //     onClose: onCloseCallback,     // Define a callback function when the timepicker is closed.
        //     onHourShow: onHourShow,       // Define a callback to enable / disable certain hours. ex: function onHourShow(hour)
        //     onMinuteShow: onMinuteShow,   // Define a callback to enable / disable certain minutes. ex: function onMinuteShow(hour, minute)

        // custom hours and minutes
        hours: {
            starts: 0,                  // first displayed hour
            ends: 23                    // last displayed hour
        },
        minutes: {
            starts: 0,                  // first displayed minute
            ends: 55,                   // last displayed minute
            interval: 5                 // interval of displayed minutes
        },
        rows: 4                         // number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2
    });

});

function agregarMarcador(){
    var x;
    var y;
    
    var ciudad = $('#ciudad').attr('value');
    var direccion = $('#direccion').attr('value');
    var fecha= $('#datepicker').attr('value');
    // var mes = document.getElementById("mes").value;
    // var anio = document.getElementById("anio").value;
    
    var hora = $('#timepicker').attr('value');
    var tipo= $("input[name='tipo']:checked").val();
    var descripcion= $('#descripcion').attr('value');
    var id = new Date;
    id = id.getTime().toString(8);
    
    geocoder = new google.maps.Geocoder();
    var email=readCookie('k').split("#",1)[0];
    var autor = readCookie('k').substring(email.length+1,readCookie('k').length);

    if (ciudad && direccion && fecha && hora) { // values are not empty
        if(!tipo){
            tipo="otros"
        }
        var address=ciudad+", "+direccion;
        geocoder.geocode( {
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                x=results[0].geometry.location.lat();
                y=results[0].geometry.location.lng();
                confirm("¿Desea crear el nuevo evento?");
                $.ajax({
                    type: "GET",              
                    url: "cgis/agregarMarcador.cgi",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    // send username and password as parameters to the Perl script
                    data: "ciudad="+ciudad+"&direccion=" +direccion+"&fecha=" +fecha+"&hora="+hora+"&tipo="+tipo+"&descripcion="+descripcion+"&x="+x+"&y="+y+"&autor="+autor+"&id="+id,
                    // script call was *not* successful
                    error: function(XMLHttpRequest, textStatus, errorThrown) { 
                        $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText 
                            + ", textStatus: " + textStatus 
                            + ", errorThrown: " +errorThrown);
                        $('div#loginResult').addClass("error");
                    }, // error 
                    // script call was successful 
                    // data contains the JSON values returned by the Perl script 
                    success: function(data){
                        if (data.error) { // script returned error
                            $('div#markerResult').text("data.error: "  +data.error);
                            $('div#markerResult').addClass("error");
                        } // if
                        else {
                            alert("Marcador creado correctamente");
                        } //else
                    } // success
                }
                ); // ajax
             
             
             
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });

      
    } // if
    else {
        $('div#markerResult').text("Introduzca ciudad, direccion, fecha y hora (y tipo si lo desea)");
        $('div#markerResult').addClass("error");
    } // else
    $('div#markerResult').fadeIn();

}
